<template>
    <!-- 搜索 v-permission="props.permission"-->
    <searchVue :list="page.search" @search="onSearch" @reset="onReset" ref="searchRef" v-if="searchVisible">
        <!-- 在搜索后面添加的内容 -->
        <template #add>
            <slot name="add"></slot>
        </template>
        <!-- 通过输入内容获取企业id -->
        <template #custom>
            <searchCompanyVue
                :data="searchCompany"
                @change="onSelectCompanyId"
                :placeholder="placeholderText"
            ></searchCompanyVue>
        </template>
    </searchVue>
    <!-- 搜索与表格之间的按钮 -->
    <div :class="['slot', page.headerOperation.length ? 'insert' : '']" ref="insertRef">
        <template v-for="item in page.headerOperation" :key="item.type">
            <section
                v-if="item.button === 'button'"
                :class="['button', 'border']"
                @click="emits('operation', { type: item.type, data: null })"
                v-permission="item.permission"
            >
                {{ item.name }}
            </section>
            <el-radio-group
                v-else-if="item.button === 'radio-button'"
                v-model="item.modelValue"
                @change="(res:any)=>{
                    item.modelValue = res
                    emits('operation', { type: item.key, data: res })
                }"
            >
                <el-radio-button v-for="child in item.radioGroup" :key="child" :label="child" />
            </el-radio-group>
        </template>
    </div>
    <!-- 表格 -->
    <div
        :class="['table', page.headerOperation.length ? 'insert' : '', page.table.isDialog ? 'dialog' : '']"
        ref="tableRef"
    >
        <el-table
            ref="multipleTableRef"
            :data="page.table.data"
            style="width: 100%; height: 100%; max-height: 100%"
            :border="true"
            @selection-change="handleSelectionChange"
            :header-cell-style="{ background: '#f5f7fa' }"
            :summary-method="getSummaries"
            :show-summary="page.table.showSummary"
        >
            <!-- 选择框 -->
            <el-table-column type="selection" width="50" v-if="page.table.selection"></el-table-column>
            <!-- 序号 -->
            <el-table-column type="index" width="54" v-if="page.table.index" label="序号" align="center" />
            <template v-for="(item, index) in page.table.describe" :key="item">
                <!-- 操作按钮 -->
                <el-table-column
                    fixed="right"
                    v-if="item.operation.length"
                    :label="item.label"
                    :width="item.width"
                    align="center"
                >
                    <template #default="scope">
                        <!-- v-permission="opera.permission" -->
                        <div class="operation">
                            <div v-for="opera in item.operation" :key="opera.type">
                                <span
                                    :class="['custom-button', opera.className]"
                                    v-if="setVisible(opera.visible as visibleType, scope.row)"
                                    @click="emits('operation', { type: opera.type, data: scope.row })"
                                    >{{ opera.name }}</span
                                >
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <!-- 滑块 开关按钮 -->
                <el-table-column v-else-if="item.switch" :label="item.label" align="center" width="90px">
                    <template #default="scope">
                        <template v-if="page.table.switch.tooltip.visible">
                            <el-tooltip :content="page.table.switch.tooltip.content" :disabled="!scope.row.status">
                                <el-switch
                                    v-permission="page.table.switch.permission"
                                    v-model="scope.row.status"
                                    inline-prompt
                                    active-text="启用"
                                    inactive-text="禁用"
                                    @change="emits('operation', { type: 'switch', data: scope.row })"
                                />
                            </el-tooltip>
                        </template>
                        <template v-else>
                            <el-switch
                                v-permission="page.table.switch.permission"
                                v-model="scope.row.status"
                                inline-prompt
                                active-text="启用"
                                inactive-text="禁用"
                                @change="emits('operation', { type: 'switch', data: scope.row })"
                            />
                        </template>

                        <!-- <slot name="switch" :index="scope.$index" :row="scope.row"></slot> -->
                    </template>
                </el-table-column>
                <!-- 判断是否存在某个字典 -->
                <el-table-column
                    v-else-if="DICT_DATA.has(item.prop)"
                    :label="item.label"
                    :sortable="page.table.sortable.includes(item.prop)"
                    :prop="item.prop"
                    :show-overflow-tooltip="true"
                    align="center"
                >
                    <template #default="scope">
                        <DictVue :data="DICT_DATA.get(item.prop)" :value="scope.row[item.prop]"></DictVue>
                    </template>
                </el-table-column>
                <!-- 多级表头 -->
                <el-table-column v-else-if="item.children.length" :label="item.label" align="center">
                    <el-table-column
                        :label="child.label"
                        v-for="(child, index) in item.children"
                        :prop="child.prop"
                        :key="child"
                        align="center"
                    >
                    </el-table-column>
                </el-table-column>
                <!-- 默认情况 -->
                <!-- width 根据表格的属性进行区分设置宽度 -->
                <el-table-column
                    v-else
                    :prop="item.prop"
                    :label="item.label"
                    :sortable="page.table.sortable.includes(item.prop)"
                    :show-overflow-tooltip="true"
                    align="center"
                    :width="item.width"
                ></el-table-column>
            </template>
        </el-table>
    </div>
    <!-- 分页 -->
    <paginationVue :pagination="page.pagination" @change="onPaginationChange" @page-size="onPaginationSize" />
</template>
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watchEffect, reactive } from 'vue'
import searchVue from '../search/Index.vue'
import paginationVue from '../Pagination.vue'
import DictVue from '../dict/Index.vue'
import { DICT_DATA } from '@/utils/dict-data'
import { ElTable } from 'element-plus'
import type { TableColumnCtx } from 'element-plus'
import searchCompanyVue from '@/components/searchCompany.vue'
import { visibleType } from '@/utils/basc-data'
import { summaryMap, setVisible } from './tableSet'

/**
 * 监听table高度
 */
const tableRef = ref(0)

/**
 * 监听搜索栏高度
 */
const searchRef = ref()

/**
 * 设置搜索栏高度
 */
const searchHeight = ref(50)

/**
 * 设置搜索栏是否显示 根据传递的list参数是否为空判断
 */
const searchVisible = ref(true)

//监听是否有插入的内容
const insertRef = ref()
const insert = ref(false)

//搜索企业id输入提示
const placeholderText = ref('')
// const isSearchCompany = ref(false)
const searchCompany = reactive({
    width: '100%',
    name: '',
    disabled: false
})
const companyId = ref('')
/**
 * 监听检索选择的公司id
 * @param id
 */
const onSelectCompanyId = (res: any) => {
    console.log('companyId', res)
    companyId.value = res.value
    searchCompany.name = res.name
}

/**
 * 接收父组件传递的参数
 */
const props = defineProps({
    page: {
        type: Object,
        default: () => {
            return {
                headerOperation: [],
                permission: [],
                pagination: {
                    pageNo: 1,
                    pageSize: 20,
                    total: 0
                },
                table: {
                    data: [],
                    describe: [],
                    selection: false,
                    index: true,
                    list: [],
                    showSummary: false,
                    summaryArray: [],
                    summaryType: '',
                    sortable: [],
                    isDialog: false,
                    switch: {
                        disabled: false,
                        permission: [],
                        tooltip: {
                            visible: false,
                            content: ''
                        }
                    }
                },
                search: []
            }
        }
    }
})

/**
 * 注册父组件的回调
 */
const emits = defineEmits(['search', 'reset', 'paginationChange', 'paginationSize', 'multiSelection', 'operation'])

/**
 * 监听点击搜索按钮
 * @param res
 */
const onSearch = (res: any) => {
    if ('custom' in res) {
        res['companyId'] = companyId.value
        res['custom'] = { companyId: companyId.value, companyName: searchCompany.name }
    }

    emits('search', res)
}

/**
 * 监听点击重置按钮
 */
const onReset = () => {
    searchCompany.name = ''
    companyId.value = ''
    emits('reset')
}

/**
 * 监听选择的当前分页
 * @param index
 */
const onPaginationChange = (index: number) => {
    emits('paginationChange', index)
}

/**
 * 监听分页大小的改变
 * @param index
 */
const onPaginationSize = (index: number) => {
    emits('paginationSize', index)
}

const multipleTableRef = ref<InstanceType<typeof ElTable>>()

/**
 * 表格全选框回调
 * @param res
 */
const handleSelectionChange = (rows: any[]) => {
    emits('multiSelection', rows)
}

// /**
//  * 获取搜索栏的高度
//  */
// const getSearchHeight = () => {
//     searchHeight.value = searchVisible.value === true ? searchRef.value.$el.clientHeight : 0
//     // console.log('insertRef', insertRef)
//     insert.value = insertRef.value.children.length ? true : false
// }

// /**
//  * 页面初次挂载完成
//  */
// onMounted(() => {
//     getSearchHeight()
//     window.addEventListener<'resize'>('resize', getSearchHeight)
// })

// /**
//  * 页面卸载之前
//  */
// onBeforeUnmount(() => {
//     window.removeEventListener<'resize'>('resize', getSearchHeight)
// })

/**
 * 监听 props 参数变化
 */

watchEffect(() => {
    searchVisible.value = props.page.search.length ? true : false
    if (searchVisible.value) {
        props.page.search.forEach((item: any) => {
            if (Object.prototype.toString.call(item) === '[object Array]') {
                placeholderText.value = item.length > 1 ? item[1] : '请输入公司名称|编号'
            }
        })
    }
})

interface SummaryMethodProps<T = any> {
    columns: TableColumnCtx<T>[]
    data: T[]
}

//设置统计尾行
const getSummaries = (param: SummaryMethodProps) => {
    const { columns, data } = param
    const sums: string[] = []
    columns.forEach((column, index) => {
        sums[index] = props.page.table.summaryArray[index]
    })
    const tds = props.page.table.isDialog
        ? document.querySelectorAll('.el-dialog .el-table__footer-wrapper tr>td')
        : document.querySelectorAll('.table .el-table__footer-wrapper tr>td')
    if (tds.length) {
        console.log('summaryType', props.page.table.summaryType)
        summaryMap.get(props.page.table.summaryType)(tds)
    }
    return sums
}
</script>
<style scoped lang="scss">
.operation {
    display: flex;
    div {
        &:first-child {
            margin-left: 12px;
        }
        &:last-child {
        }
    }
}
.table {
    margin: 0 0 16px 0;
}
.slot.insert {
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.swich-box {
    width: 48px;
    height: 20px;
    background-color: #409eff;
    border-radius: 10px;
    overflow: hidden;
    position: relative;
    cursor: pointer;
    transition: all 0.2s;
    &.active {
        background-color: #dcdfe6;
        p {
            text-align: left;
        }
        span {
            left: calc(100% - 2px - 16px);
        }
    }
    p {
        font-size: 12px;
        box-sizing: border-box;
        line-height: 20px;
        color: #fff;
        padding: 0 4px;
        display: block;
        width: 100%;
        text-align: right;
        transition: all 0.2s;
    }
    span {
        transition: all 0.2s;
        display: block;
        width: 16px;
        height: 16px;
        background-color: #fff;
        border-radius: 50%;
        position: absolute;
        top: 2px;
        left: 2px;
    }
}
</style>
